package nl.ejvos.bgpgames.cbbchess.server;

import nl.ejvos.bgpgames.cbbchess.shared.MoveMessage;
import nl.ejvos.bgpgames.cbbchess.shared.OpponentMovedMessage;

import com.hu.bgp.framework.GameContext;
import com.hu.bgp.framework.GameState;
import com.hu.bgp.framework.Server;
import com.hu.bgp.framework.clientapi.ClientToServerMessage;
import com.hu.bgp.server.Player;
import com.hu.bgp.shared.OverviewUpdateMessage;

public class ChessServer extends Server
{
	private Player whitePlayer;
	private Player blackPlayer;

	public ChessServer(GameContext gameContext)
	{
		super(gameContext);
		gameContext.changeState(GameState.WAITING_FOR_PLAYERS);
	}

	public void handleMessage(ClientToServerMessage message, Player fromPlayer)
	{
		if (message instanceof MoveMessage)
		{
			MoveMessage cm = (MoveMessage) message;
			broadcastMessage(new OpponentMovedMessage(fromPlayer.getUuidString(), cm.getX(), cm.getY(), cm.getToX(), cm.getToY()));
		}
	}

	public void start()
	{
		updateOverview();
	}

	private void updateOverview()
	{
		StringBuilder overview = new StringBuilder();
		for (Player p : gameContext.getPlayers())
		{
			overview.append("player: " + p.getProfile().getName() + "\n");
		}
		OverviewUpdateMessage message = new OverviewUpdateMessage(overview.toString());
		broadcastMessage(message);
	}

	public void playerJoined(Player player)
	{
		if (gameContext.getState() == GameState.WAITING_FOR_PLAYERS)
		{
			if (gameContext.getPlayers().size() == 2)
			{
				whitePlayer = gameContext.getInitialPlayer();
				blackPlayer = gameContext.getPlayers().get(1);
				gameContext.changeState(GameState.RUNNING);
				broadcastMinimumPlayersReachedEvent();
			}
		}
	}

	public void playerLeft(Player player)
	{
	}

	public void playerRejoined(Player player)
	{
	}
}
